﻿using MPSystem.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Windows;
using System.Windows.Input;
using Ay.MvcFramework;
using Ay.Framework.DataCreaters;
using Ay.Framework.WPF;
using Ay.Framework.WPF.Controls;
using MPSystem.Execl;
using System.Data;
using System.Threading;
using Base.BLL;
using System.Windows.Navigation;
using MPSystem.Views.YFQ;
using System.Windows.Controls;
using System.Windows.Forms;
using System.IO;
using MPSystem.Util;

namespace MPSystem.Controllers
{

    public class DataQuery_CCController : Controller
    {
        public static DataQuery_CCController Me = null;
        Common common = new Common();
        public static int gzmbh = 0;
        public class DataQuery_CCSearchModel : Model
        {
            private string _OrderCondition;

            /// <summary>
            /// 未填写
            /// </summary>
            public string OrderCondition
            {
                get { return _OrderCondition; }
                set { Set(ref _OrderCondition, value); }
            }

            private int _CboQCSelect = -1;

            /// <summary>
            /// 测区选择
            /// </summary>
            public int CboQCSelect
            {
                get { return _CboQCSelect; }
                set { Set(ref _CboQCSelect, value); }
            }

            private int _CboGZMSelect = -1;

            /// <summary>
            /// 工作面选择
            /// </summary>
            public int CboGZMSelect
            {
                get { return _CboGZMSelect; }
                set { Set(ref _CboGZMSelect, value); }
            }
            private string _SearchName;

            /// <summary>
            /// 未填写
            /// </summary>
            public string SearchName
            {
                get { return _SearchName; }
                set { Set(ref _SearchName, value); }
            }
            private int _PageSize = 30;

            /// <summary>
            /// 未填写
            /// </summary>
            public int PageSize
            {
                get { return _PageSize; }
                set { Set(ref _PageSize, value); }
            }
            private int _PageIndex = 0;

            /// <summary>
            /// 未填写
            /// </summary>
            public int PageIndex
            {
                get { return _PageIndex; }
                set { Set(ref _PageIndex, value); }
            }

            private int _PageCount = 0;
            public int PageCount
            {
                get { return _PageCount; }
                set { Set(ref _PageCount, value); }
            }
            private int _Start = 0;
            public int Start
            {
                get { return _Start; }
                set { Set(ref _Start, value); }
            }
            private int _End = 0;
            public int End
            {
                get { return _End; }
                set { Set(ref _End, value); }
            }
            private int _IndexCQ = 0;
            public int IndexCQ
            {
                get { return _IndexCQ; }
                set { Set(ref _IndexCQ, value); }
            }
            private int _IndexGZM = 0;
            public int IndexGZM
            {
                get { return _IndexGZM; }
                set { Set(ref _IndexGZM, value); }
            }

            private DateTime _DateFrom = DateTime.Now;

            /// <summary>
            /// 未填写
            /// </summary>
            public DateTime DateFrom
            {
                get { return _DateFrom; }
                set { Set(ref _DateFrom, value); }
            }
            private DateTime _DateTo = DateTime.Now;

            /// <summary>
            /// 未填写
            /// </summary>
            public DateTime DateTo
            {
                get { return _DateTo; }
                set { Set(ref _DateTo, value); }
            }

        }

        List<Dictionary<string, string>> conditons = new List<Dictionary<string, string>>();
        private string bh = "", dtStart = "", dtEnd = "", _sfbj = "", _jq = "", zbhs = "", _byZBH = "true", where = "";


        public ObservableCollection<DataQuery_CCModel> AllDatas { get; set; } = new ObservableCollection<DataQuery_CCModel>();
        public DataQuery_CCSearchModel SearchModel { get; set; } = new DataQuery_CCSearchModel();

        private AyPagingDto<DataQuery_CCModel> _Result;

        /// <summary>
        /// 未填写
        /// </summary>
        public AyPagingDto<DataQuery_CCModel> Result
        {
            get { return _Result; }
            set { Set(ref _Result, value); }
        }


        private ObservableCollection<IAyCheckedItem> _QCCbo = new ObservableCollection<IAyCheckedItem>();

        public ObservableCollection<IAyCheckedItem> QCCbo
        {
            get { return _QCCbo; }
            set { Set(ref _QCCbo, value); }
        }
        private ObservableCollection<IAyCheckedItem> _GZMCbo = new ObservableCollection<IAyCheckedItem>();

        public ObservableCollection<IAyCheckedItem> GZMCbo
        {
            get { return _GZMCbo; }
            set { Set(ref _GZMCbo, value); }
        }

        private bool _IsBusy = false;
        public bool IsBusy
        {
            get { return _IsBusy; }
            set { Set(ref _IsBusy, value); }
        }
        /// <summary>
        /// 搜索
        /// </summary>
        public ActionResult Search { get; private set; }

        /// <summary>
        /// 导出
        /// </summary>
        public ActionResult ExportExecl { get; private set; }

        public ActionResult CqChanged { get; private set; }


        public DataQuery_CCController() : base()
        {
            Me = this;
            Result = new AyPagingDto<DataQuery_CCModel>();
            var rcq = ConfigService.GetCQ(true);
            common.LoadCombox_IE(QCCbo, rcq);
            if (rcq.Count() == 0)
            {
                AyMessageBox.ShowError("没有测区！");
                return;
            }
            SearchModel.CboQCSelect = rcq.ElementAt(0).CQBH;
            SearchModel.IndexCQ = 1;

            CqChanged = inParam =>
            {
                if (QCCbo.Count == 0) return;
                int cqbh = (int)inParam;
                //工作面
                if (cqbh == -1)
                    SearchModel.CboQCSelect = -1;
                var rgzm = ConfigService.GetGZM(SearchModel.CboQCSelect);
                common.LoadCombox_IE(GZMCbo, rgzm);
                if (rgzm.Count() == 0) return;
                SearchModel.CboGZMSelect = rgzm.ElementAt(0).GZMBH;
                SearchModel.IndexGZM = 1;
            };
            CqChanged(SearchModel.CboQCSelect);
            Search = inParam =>
            {
                if (SearchModel.CboQCSelect == -1 || SearchModel.CboGZMSelect == -1)
                {
                    AyMessageBox.ShowError("请先选择测区和工作面！");
                    return;
                }
                if (AyCommon.ToInt(inParam) == 1)
                {
                    SearchModel.PageIndex = 1;
                }
                gzmbh = SearchModel.CboGZMSelect;
                if (SearchModel.PageIndex > 0)
                {
                    SearchData();
                }
                else
                {
                    SearchModel.PageIndex = 1;
                }
            };
            ExportExecl = inParam =>
            {
                //ExportExcel ExpEX = new Execl.ExportExcel();
                //try
                //{

                //    DataTable dt = new DataTable();
                //    dt = IenumerableToTable.AsDataTable<DataQuery_CCModel>(AllDatas);
                //    ExpEX.ExportGridExcel_Table("综采数据查询", dt, "", 18);
                //}
                //catch (Exception ex) { }
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.DefaultExt = "xls";
                saveDialog.Filter = "Excel文件|*.xls";
                saveDialog.FileName = "综采数据导出";
                if (saveDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                string saveFileName = saveDialog.FileName;
                if (!ExcelHelper.FileEditable(saveFileName))
                {
                    AyMessageBox.ShowError("文件被占用，请关闭文件" + saveFileName);
                    return;
                }
                var cond = DataQuery_CCDataQuery_CC_Conditon.Me.Cond;
                ViewBag.IsBusy = true;

                AyThread.Instance.RunNew(() =>
                {
                    if (cond.Count == 0) return;
                    dtStart = cond["dtStart"];
                    dtEnd = cond["dtEnd"];
                    _jq = cond["jq"];
                    _sfbj = cond["sfbj"];
                    zbhs = cond["bhs"];
                    _byZBH = cond["byZBH"];
                    where = cond["where"];
                    DataZcService ds = new DataZcService();

                    string[] s = zbhs.Split(',');
                    int[] bhs = new int[s.Length];//编号列表
                    for (int b = 0; b < s.Length; b++)
                    {
                        bhs[b] = AyCommon.ToInt(s[b]);
                    }
                    bool byZBH = true;// true:按压力分机查询 false:综采支架查询
                    if (_byZBH == "true")
                        byZBH = true;
                    else byZBH = false;

                    int jq = AyCommon.ToInt(_jq);
                    int sfbj = AyCommon.ToInt(_sfbj);//是否报警，-1：全部 0：未报警 1：报警
                    DateTime db = AyCommon.ToDateTime(dtStart), de = AyCommon.ToDateTime(dtEnd) + new TimeSpan(23, 59, 59);
                    //db = new DateTime(2018, 12, 20); de = new DateTime(2018, 12, 30);
                    //统计总数
                    int TotalSum = ds.QueryCount(SearchModel.CboQCSelect, SearchModel.CboGZMSelect, byZBH, bhs, db, de,
                      jq, where, sfbj);
                    if(TotalSum>=65535)
                    {
                        AyMessageBox.ShowError("数据共"+ TotalSum+"行，超过Excel限制(65535)，请缩短查询时间段！");
                        AyThread.Instance.RunUI(() =>
                        {
                            ViewBag.IsBusy = false;
                        });
                        return;
                    }
                    ds.Export(saveFileName,SearchModel.CboQCSelect, SearchModel.CboGZMSelect, byZBH, bhs, db, de,
                        jq, where, sfbj);
                    AyMessageBox.ShowInformation("已导出至" + saveFileName);
                    AyThread.Instance.RunUI(() =>
                    {
                        ViewBag.IsBusy = false;
                    });
                });
            };

            HSearch = inParam =>
            {
                if (SearchModel.CboQCSelect == -1 || SearchModel.CboGZMSelect == -1)
                {
                    AyMessageBox.ShowError("请先选择测区和工作面！");
                    return;
                }
                gzmbh = SearchModel.CboGZMSelect;
                ShowNavigationWindow("高级查询", "/Views/YFQ/DataQuery_CC_Conditon.xaml", 600, 500);
            };

        }

        public void SearchData()
        {
            var cond = DataQuery_CCDataQuery_CC_Conditon.Me.Cond;
            AllDatas.Clear();
            ViewBag.IsBusy = true;

            AyThread.Instance.RunNew(() =>
            {
                if (cond.Count == 0) return;
                dtStart = cond["dtStart"];
                dtEnd = cond["dtEnd"];
                _jq = cond["jq"];
                _sfbj = cond["sfbj"];
                zbhs = cond["bhs"];
                _byZBH = cond["byZBH"];
                where = cond["where"];
                DataZcService ds = new DataZcService();

                string[] s = zbhs.Split(',');
                int[] bhs = new int[s.Length];//编号列表
                for (int b = 0; b < s.Length; b++)
                {
                    bhs[b] = AyCommon.ToInt(s[b]);
                }
                bool byZBH = true;// true:按压力分机查询 false:综采支架查询
                if (_byZBH == "true")
                    byZBH = true;
                else byZBH = false;


                int jq = AyCommon.ToInt(_jq);
                int sfbj = AyCommon.ToInt(_sfbj);//是否报警，-1：全部 0：未报警 1：报警
                DateTime db = AyCommon.ToDateTime(dtStart), de = AyCommon.ToDateTime(dtEnd) + new TimeSpan(23, 59, 59);
                //db = new DateTime(2017, 1, 1); de = new DateTime(2018, 9, 2);
                //统计总数
                int TotalSum = ds.QueryCount(SearchModel.CboQCSelect, SearchModel.CboGZMSelect, byZBH, bhs, db, de,
                  jq, where, sfbj);
                var rs = ds.Query(SearchModel.CboQCSelect, SearchModel.CboGZMSelect, byZBH, bhs, db, de,
                    jq, where, sfbj, SearchModel.PageIndex - 1, SearchModel.PageSize);
                AyThread.Instance.RunUI(() =>
                {
                    foreach (var r in rs)
                    {
                        DataQuery_CCModel cc = new DataQuery_CCModel();
                        cc.FZBH = r.ZBH;
                        cc.ZJBH = r.DYZJBH;
                        cc.AZWZ = r.WZ;
                        cc.ZT = r.P1* r.P2 == 0?"故障":(r.SFBJ?"报警":"正常");
                        cc.P1 = r.P1;
                        cc.P2 = r.P2;
                        cc.P3 = r.P3;
                        cc.X = r.Q1;
                        cc.Y = r.Q2;
                        cc.ZDTIME = r.ZDATETIME;
                        AllDatas.Add(cc);
                    }
                    ViewBag.IsBusy = false;
                    if (AllDatas.Count > 0)
                    {
                        Result.Data = AllDatas;
                        Result.Total = TotalSum;
                        int _count = TotalSum / SearchModel.PageSize;
                        SearchModel.PageCount = TotalSum % SearchModel.PageSize == 0 ? _count : _count + 1;
                        int _start = (SearchModel.PageIndex - 1) * SearchModel.PageSize + 1;
                        SearchModel.Start = _start > 0 ? _start : 0;
                        int _end = SearchModel.PageIndex * SearchModel.PageSize;
                        SearchModel.End = _end > TotalSum ? TotalSum : _end;
                    }
                    else
                    {
                        SearchModel.PageIndex = 0;
                        AyMessageBox.ShowInformation("没有符合查询条件的记录！");
                    }
                });
            });

        }


        public ActionResult HSearch { get; private set; }
        public ActionResult NSearch { get; private set; }

        public static NavigationWindow window = null;
        /// <summary>/// 使用NavigationWindow弹出页面/// </summary>

        private void ShowNavigationWindow(string title, string uri, int width, int height)
        {
            if (window == null)
            {
                window = new NavigationWindow();
                window.Title = title;
                window.Width = width;
                window.Height = height;
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                window.ResizeMode = ResizeMode.NoResize;
                window.Source = new Uri(uri, UriKind.Relative);
                window.ShowsNavigationUI = false;
                window.Closing += Window_Closing1;
            }
            else
            {
                DataQuery_CCDataQuery_CC_Conditon.Me.LoadBH();
            }
            window.ShowDialog();

        }
        private void Window_Closing1(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //ConditonsModel.Name = cqm.Ckmc;
            DataQuery_CCDataQuery_CC_Conditon.Me.UpdateCond();
            window.Hide();
            SearchModel.PageIndex = 1;
            Me.SearchData();
            e.Cancel = true;
        }
    }
}
